<template>
	<view class="container">
		<view class="btn">
			<button type="primary" @click="publish" size="mini">发表</button>
		</view>
		<view class="content">
			<textarea v-model="content" cols="30" rows="10" placeholder="这一刻的想法..."></textarea>
		</view>
		<view class="imglist">
			<!-- 上传图片的缩略图 -->
			<view class="imgs" v-if="imgList.length">
				<image v-for="(item,index) in imgList" :key="index" :src="item" mode="aspectFill" class="img"></image>
			</view>
			<view class="add" @click="chooseimg">
				+
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref } from "vue"

	import * as api from "@/api/comment.js"

	import useUser from "@/store/users.js"

	let userStore = useUser()

	//选择图片后 临时路径
	let imgList = ref([])
	//上传给后台的图片字段
	let imgListParam = []
	//评论的内容
	let content = ref()

	//发布评论的方法

	let publish = async () => {
		uni.showLoading({
			title:'正在发布'
		})
		let unid = userStore.userInfo.unid;
		try {
			let res = await api.addCommmentApi({
				reply_unid: unid,
				imgList: imgListParam,
				content: content.value
			})

			content.value = ""
			imgList.value = [];
			imgListParam = []
			uni.hideLoading()
			//页面返回评论页
			uni.navigateBack()
		} catch (e) {
			uni.hideLoading()
			console.log(e.toString())
		}

	}

	//选择图片
	let chooseimg = () => {
		// 一种是拍照 另一种是从相册获取
		uni.chooseImage({
			//裁剪图片
			crop: {
				quality: 40,
				width: 400,
				height: 400
			},
			success(res) {

				// console.log(res)
				imgList.value = [...imgList.value, ...res.tempFilePaths];
				//调用uni.uploadFile上传图片
				res.tempFilePaths.forEach((filePath, index) => {
					uni.uploadFile({
						url: "https://chst.vip/upload/uploadImg",
						filePath,
						name: "img",
						success(res) {
							let data = JSON.parse(res.data)
							imgListParam.push(data.imgUrl)
							// console.log(res)
						},
						faile(e) {
							console.log(e.toString())
						}
					})
				})
			},
			faile(e) {
				uni.showToast({
					'icon': 'error',
					title: e.toString()
				})
			}
		})
	}
</script>

<style lang="scss">
	.container {
		padding: 40rpx;
		background: #f7f7f7;
		width: 750rpx;
		.btn {
			text-align: right;
			padding-right:20px;
			button {
				margin:20px;
			}
		}
		.content {
			width: 100%;

			textarea {
				width: 90%;
				min-height: 50px;
				color: #000;
			}
		}

		.imglist {
			width: 750rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.img,
			.add {
				width: 160rpx;
				height: 80px;
				margin-left: 10px;
				
				// border: 1px solid #424242;
			}

			.add {
				line-height: 80px;
				text-align: center;
				font-size: 40px;
				background:#424242;
				color:#fff;
			}
		}
	}
</style>